from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import math

edges_of_polygon = 6  # 多边形边数
r = 10  # 多边形外接圆的半径
cx, cy = 0, 0  # 圆心坐标
theta = 0.0  # 旋转的初始角度


def idle():
    global theta  # 使用全局变量theta
    theta += 0.001
    if theta >= 2 * math.pi:
        theta -= 2 * math.pi
    glutPostRedisplay()


def reshape(w, h):
    global r  # 使用全局变量r
    glMatrixMode(GL_PROJECTION)  # 进入投影矩阵操作
    glLoadIdentity()  # 初始化矩阵堆栈
    gluOrtho2D(-1.5 * r * w / h, 1.5 * r * w / h, -1.5 * r, 1.5 * r)  # 设置裁剪窗口大小，并锁定宽高比
    glViewport(0, 0, w, h)  # 设置视口大小
    glMatrixMode(GL_MODELVIEW)  # 进入模型矩阵操作


def display():
    global r, theta, edges_of_polygon
    glClearColor(1, 1, 1, 1)
    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(1.0, 0, 0)  # 红色绘制颜色
    # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)  # 线框模式
    glLineWidth(1)
    glBegin(GL_POLYGON)
    for i in range(edges_of_polygon):
        glVertex2f(r * math.cos(theta + i * 2 * math.pi / edges_of_polygon),
                   r * math.sin(theta + i * 2 * math.pi / edges_of_polygon))
    glEnd()
    glutSwapBuffers()  # 双缓存必须使用该函数（单缓存时用glFlush）


if __name__ == '__main__':
    glutInit()
    glutInitWindowSize(700, 700)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)  # 使用双缓存
    glutCreateWindow("旋转多边形".encode("GBK"))
    glutDisplayFunc(display)
    glutReshapeFunc(reshape)
    glutIdleFunc(idle)
    glutMainLoop()
